﻿using qqdest.DAO;
using qqdest.DaoImpl;
using qqdest.Model;
using qqdest.Service;
using qqdest.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace qqdest.ServiceImpl
{
    public class UserServuceImpl : IUserService
    {
        public const int USER_COUNT = 6;

        private IUserDao userDao = null;

        public UserServuceImpl()
        {
            this.userDao = new UserDaoImpl();
        }

        bool IUserService.Login(User user)
        {
            User userFromDB = userDao.findUserByUserName(user.username);
            return (userFromDB != null && userFromDB.username == user.username && userFromDB.password == user.password);
        }

        // TODO: 长度检查还未实现
        /// <summary>
        /// 检查用户是否输入内容
        /// </summary>
        /// <returns></returns>
        public bool CheckUserInput(string str, int len)
        {
            return !(string.IsNullOrEmpty(str)) && str.Length >= USER_COUNT;
        }

        bool IUserService.CheckUserInput(string str, int len)
        {
            return !string.IsNullOrEmpty(str) && str.Length >= len;
        }

        bool IUserService.Register(User user)
        {
            // 长度检查
            if(!CheckUserInput(user.nickname, 1 ) || !CheckUserInput(user.password, 6) || !CheckUserInput(user.phonenumber, 11))
            {
                return false;
            }

            // 手机号检查
            if (!PhoneUtil.IsValidPhoneNumber(user.phonenumber))
            {
                return false;
            }

            // 检查手机号是否注册过
            if (userDao.findUserByPhoneNumber(user.phonenumber) != null)
            {
                return false;
            }

            // 随机生成用户名
            do
            {
                string userName = RandomUtil.GenerateRandomDigits(6);
                User userByUsername = userDao.findUserByUserName(userName);
                if (userByUsername == null)
                {
                    user.username = userName;
                    break;
                }
            } while (true);

            // 插入数据库
            userDao.InsertUser(user);

            return true;   
        }
    }
}
